package com.wendy.service.impl;

import com.wendy.mapper.UserMapper;
import com.wendy.model.BaseModel;
import com.wendy.model.User;
import com.wendy.service.BaseService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import tk.mybatis.mapper.common.Mapper;

import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.util.Date;
import java.util.List;

/**
 * @author zhuwending
 */
@Slf4j
public abstract class BaseServiceImpl<T> implements BaseService<T> {

    @Autowired
    protected Mapper<T> mapper;
    private Class genericClass = (Class) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
    @Autowired
    private UserMapper userMapper;

    @Override
    public T selectByKey(Object key) {
        return mapper.selectByPrimaryKey(key);
    }

    @Override
    public int save(T entity) {
        return mapper.insert(entity);
    }

    @Override
    public int delete(Object o) {
        return mapper.deleteByPrimaryKey(o);
    }

    @Override
    public int updateAll(T entity) {
        return mapper.updateByPrimaryKey(entity);
    }

    @Override
    public int updateNotNull(T entity) {
        return mapper.updateByPrimaryKeySelective(entity);
    }

    @Override
    public List<T> selectByExample(Object example) {
        return mapper.selectByExample(example);
    }

    @Override
    public User currentUser() {
        String username = SecurityContextHolder.getContext().getAuthentication().getName();
        System.out.println("base:" + username);
        return userMapper.selectUserByUsername(username);
    }

    @Override
    public int insert(T entity) {
        Class superClass = entity.getClass().getSuperclass();
        if (null != superClass) {
            if (BaseModel.class.equals(superClass)) {
                Method[] methodsOfBaseModel = superClass.getMethods();
                Date date = new Date();
                for (Method method : methodsOfBaseModel) {
                    try {
                        switch (method.getName()) {
                            case "setCreateUser":
                            case "setUpdateUser":
                                String username = SecurityContextHolder.getContext().getAuthentication().getName();
                                method.invoke(entity, username);
                                break;
                            case "setCreateTime":
                            case "setUpdateTime":
                                method.invoke(entity, date);
                                break;
                            case "setDeleted":
                                method.invoke(entity, false);
                            default:
                        }
                    } catch (Exception e) {
                        log.error("error", e);
                    }
                }
            }
        }
        return mapper.insert(entity);
    }

    @Override
    public int update(T entity) {
        Class superClass = entity.getClass().getSuperclass();
        if (null != superClass) {
            if (BaseModel.class.equals(superClass)) {
                Method[] methodOfBaseModel = superClass.getMethods();
                Date date = new Date();
                for (Method method : methodOfBaseModel) {
                    try {
                        switch (method.getName()) {
                            case "setUpdateUser":
                                String username = SecurityContextHolder.getContext().getAuthentication().getName();
                                method.invoke(entity, username);
                                break;
                            case "setUpdateTime":
                                method.invoke(entity, date);
                                break;
                            default:
                        }
                    } catch (Exception e) {
                        log.error("error", e);
                    }
                }
            }
        }
        return mapper.updateByPrimaryKeySelective(entity);
    }

    @Override
    @SuppressWarnings("unchecked")
    public int logicDelete(String ids) {
        int row = 0;
        if (StringUtils.isNotBlank(ids)) {
            try {
                Object entity = genericClass.newInstance();
                Class superClass = genericClass.getSuperclass();
                String[] idArray = ids.split(",");
                for (String id : idArray) {
                    if (BaseModel.class.equals(superClass)) {
                        Method[] methodsOfBaseModel = genericClass.getMethods();
                        for (Method method : methodsOfBaseModel) {
                            switch (method.getName()) {
                                case "setId":
                                    method.invoke(entity, Long.valueOf(id));
                                    break;
                                case "setDeleted":
                                    method.invoke(entity, true);
                                    break;
                                default:
                            }
                        }
                        row = update((T) entity);
                        if (row != 1) {
                            break;
                        }
                    }
                }
            } catch (Exception e) {
                log.error("logic delete error", e);
                throw new RuntimeException("logic delete error", e);
            }
        }
        return row;
    }
}
